/*
 * AddPurchase.java
 *
 * Created on Jan 15, 2011, 3:13:53 PM
 */
package edu.rit.varapp.graphical;

import java.util.Arrays;
import edu.rit.varapp.datalayer.Customer;
import edu.rit.varapp.datalayer.CustomerOps;
import edu.rit.varapp.datalayer.Module;
import edu.rit.varapp.datalayer.ModuleOps;
import edu.rit.varapp.utilities.ExceptionUtils;
import java.awt.Dimension;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import javax.swing.SpinnerNumberModel;

import static edu.rit.varapp.utilities.ValidationUtils.*;
import static edu.rit.varapp.utilities.StringUtils.emptyString;

/**
 * This view pane will allow a user to view extensive module information.
 * @author Eric Kisner
 */
public class DisplayPurchase extends AbstractView {

    private final CustomerOps cOps = new CustomerOps();
    private final ModuleOps mOps = new ModuleOps();
    private AdminPurchaseInfo parent;
    private static final int VIEW_WIDTH = 728;
    private int serialNumber;
    private static final int VIEW_HEIGHT = 498;

    /** Creates new form AddPurchase */
    public DisplayPurchase( AdminPurchaseInfo parent, Module module, Customer customer ) {
        super( new Dimension( VIEW_WIDTH, VIEW_HEIGHT ) );
        this.parent = parent;
        initComponents();
        showModule( module, customer );
    }

    private void showModule( Module module, Customer customer ) {
        //Sets serial number
        serialNumber = module.getSerialNumber();

        //Sets all fields to Module and Customer Data
        licensecodeField.setText( module.getLicenseCode() );
        serialnumberField.setText( module.getSerialNumber() + "" );
        contactNameField.setText( customer.getContactName() );
        companyField.setText( customer.getCompanyName() );
        locationField.setText( module.getLocation() );
        expirationDateField.setText( module.getSupportExpDate() );
        scannerModelField.setText( module.getScannerModel() );
        versionField.setText( module.getVersion() );
        purchaseDateField.setText( module.getPurchaseDate() );
        ((SpinnerNumberModel) desktopsField.getModel()).setValue( module.getDesktops() );
        ((SpinnerNumberModel) readersField.getModel()).setValue( module.getReaders() );
        ((SpinnerNumberModel) verifiersField.getModel()).setValue( module.getVerifiers() );
        ((SpinnerNumberModel) designersField.getModel()).setValue( module.getDesigners() );
        ((SpinnerNumberModel) scanstationsField.getModel()).setValue( module.getScanStations() );
        ((SpinnerNumberModel) remotestationsField.getModel()).setValue( module.getRemoteCaptureStations() );
        ((SpinnerNumberModel) ampsField.getModel()).setValue( module.getAmps() );

        if( module.isEform() ) {
            eFormBtnGrp.setSelected( eFormY.getModel(), true );
        }
        if( module.isFirstLine() ) {
            firstLineBtnGrp.setSelected( firstLineY.getModel(), true );
        }
        if( module.isTechSupport() ) {
            techSupportBtnGrp.setSelected( techSupY.getModel(), true );
        }
    }

     /**
     * Validates any input for the text fields of this GUI.
     * @return True if all fields are valid, else false.
     */
    private boolean validateInput() {
        String[] methodNames = {
            "VarCharLength", "Name","VarCharLength", "Date",
            "Date","VarCharLength", "NumLength"
        };
        String[] messages = {
            "Company Name", "Contact Name (ex. John Smith)", "Location",
            "Expiration Date (ex. YYYY-MM-DD)",
            "Purchase Date (ex. YYYY-MM-DD)", "License Code", "Serial Number"
        };
        String[] values = {
            companyField.getText(), contactNameField.getText(), locationField.getText(),
            expirationDateField.getText(), purchaseDateField.getText(),
            licensecodeField.getText(), serialnumberField.getText()
        };

        String errorMessage = runValidateMethodList( Arrays.asList( methodNames ),
                                                     Arrays.asList( messages ),
                                                     Arrays.asList( values ) );
        if( errorMessage.equals( emptyString() ) ) {
            return true;
        } else {
            JOptionPane.showMessageDialog( rootPane, errorMessage );
            return false;
        }
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings( "unchecked" )
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        eFormBtnGrp = new javax.swing.ButtonGroup();
        techSupportBtnGrp = new javax.swing.ButtonGroup();
        firstLineBtnGrp = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        serialnumberField = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        licensecodeField = new javax.swing.JTextField();
        usernameLabel = new javax.swing.JLabel();
        contactNameField = new javax.swing.JTextField();
        usernameLabel2 = new javax.swing.JLabel();
        desktopsField = new javax.swing.JSpinner();
        companyLabel = new javax.swing.JLabel();
        companyField = new javax.swing.JTextField();
        usernameLabel3 = new javax.swing.JLabel();
        readersField = new javax.swing.JSpinner();
        jLabel2 = new javax.swing.JLabel();
        locationField = new javax.swing.JTextField();
        usernameLabel4 = new javax.swing.JLabel();
        verifiersField = new javax.swing.JSpinner();
        usernameLabel1 = new javax.swing.JLabel();
        expirationDateField = new javax.swing.JTextField();
        usernameLabel5 = new javax.swing.JLabel();
        designersField = new javax.swing.JSpinner();
        usernameLabel9 = new javax.swing.JLabel();
        scannerModelField = new javax.swing.JTextField();
        usernameLabel6 = new javax.swing.JLabel();
        scanstationsField = new javax.swing.JSpinner();
        usernameLabel10 = new javax.swing.JLabel();
        versionField = new javax.swing.JTextField();
        usernameLabel7 = new javax.swing.JLabel();
        remotestationsField = new javax.swing.JSpinner();
        usernameLabel11 = new javax.swing.JLabel();
        purchaseDateField = new javax.swing.JTextField();
        usernameLabel8 = new javax.swing.JLabel();
        ampsField = new javax.swing.JSpinner();
        jPanel2 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        eFormY = new javax.swing.JRadioButton();
        eFormN = new javax.swing.JRadioButton();
        jLabel4 = new javax.swing.JLabel();
        techSupY = new javax.swing.JRadioButton();
        techSupN = new javax.swing.JRadioButton();
        jLabel5 = new javax.swing.JLabel();
        firstLineY = new javax.swing.JRadioButton();
        firstLineN = new javax.swing.JRadioButton();
        applyChangesButton = new javax.swing.JButton();
        backButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Edit Purchase Information");
        setMinimumSize(new java.awt.Dimension(727, 465));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });
        getContentPane().setLayout(null);

        jPanel1.setPreferredSize(new java.awt.Dimension(666, 224));
        jPanel1.setLayout(new java.awt.GridLayout(8, 4, 10, 0));

        jLabel6.setText("Serial Number:");
        jPanel1.add(jLabel6);
        jPanel1.add(serialnumberField);

        jLabel1.setText("License Code:");
        jPanel1.add(jLabel1);
        jPanel1.add(licensecodeField);

        usernameLabel.setText("Contact Name:");
        jPanel1.add(usernameLabel);

        contactNameField.setEditable(false);
        jPanel1.add(contactNameField);

        usernameLabel2.setText("Desktops:");
        jPanel1.add(usernameLabel2);
        jPanel1.add(desktopsField);

        companyLabel.setText("Company Name:");
        jPanel1.add(companyLabel);

        companyField.setEditable(false);
        jPanel1.add(companyField);

        usernameLabel3.setText("Readers:");
        jPanel1.add(usernameLabel3);
        jPanel1.add(readersField);

        jLabel2.setText("Location:");
        jPanel1.add(jLabel2);
        jPanel1.add(locationField);

        usernameLabel4.setText("Verifiers:");
        jPanel1.add(usernameLabel4);
        jPanel1.add(verifiersField);

        usernameLabel1.setText("Support Expiration Date:");
        jPanel1.add(usernameLabel1);
        jPanel1.add(expirationDateField);

        usernameLabel5.setText("Designers:");
        jPanel1.add(usernameLabel5);
        jPanel1.add(designersField);

        usernameLabel9.setText("Scanner Model:");
        jPanel1.add(usernameLabel9);
        jPanel1.add(scannerModelField);

        usernameLabel6.setText("Scan Stations:");
        jPanel1.add(usernameLabel6);
        jPanel1.add(scanstationsField);

        usernameLabel10.setText("Version:");
        jPanel1.add(usernameLabel10);
        jPanel1.add(versionField);

        usernameLabel7.setText("Remote Capture Stations:");
        jPanel1.add(usernameLabel7);
        jPanel1.add(remotestationsField);

        usernameLabel11.setText("Purchase Date:");
        jPanel1.add(usernameLabel11);
        jPanel1.add(purchaseDateField);

        usernameLabel8.setText("AMPs:");
        jPanel1.add(usernameLabel8);
        jPanel1.add(ampsField);

        getContentPane().add(jPanel1);
        jPanel1.setBounds(20, 20, 666, 224);

        jPanel2.setLayout(new java.awt.GridLayout(3, 3, 2, 0));

        jLabel3.setText("eForm:");
        jPanel2.add(jLabel3);

        eFormBtnGrp.add(eFormY);
        eFormY.setText("Yes");
        jPanel2.add(eFormY);

        eFormBtnGrp.add(eFormN);
        eFormN.setSelected(true);
        eFormN.setText("No");
        jPanel2.add(eFormN);

        jLabel4.setText("Tech Support:");
        jPanel2.add(jLabel4);

        techSupportBtnGrp.add(techSupY);
        techSupY.setText("Yes");
        jPanel2.add(techSupY);

        techSupportBtnGrp.add(techSupN);
        techSupN.setSelected(true);
        techSupN.setText("No");
        jPanel2.add(techSupN);

        jLabel5.setText("First Line:");
        jPanel2.add(jLabel5);

        firstLineBtnGrp.add(firstLineY);
        firstLineY.setText("Yes");
        jPanel2.add(firstLineY);

        firstLineBtnGrp.add(firstLineN);
        firstLineN.setSelected(true);
        firstLineN.setText("No");
        jPanel2.add(firstLineN);

        getContentPane().add(jPanel2);
        jPanel2.setBounds(220, 260, 300, 120);

        applyChangesButton.setText("Apply Changes");
        applyChangesButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                applyChangesButtonActionPerformed(evt);
            }
        });
        getContentPane().add(applyChangesButton);
        applyChangesButton.setBounds(200, 400, 150, 23);

        backButton.setText("Back");
        backButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backButtonActionPerformed(evt);
            }
        });
        getContentPane().add(backButton);
        backButton.setBounds(380, 400, 130, 23);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        parent.setVisible( true );
        parent.refreshGUI();
    }//GEN-LAST:event_formWindowClosed

    private void applyChangesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_applyChangesButtonActionPerformed
        if (validateInput()) {
            int newSerialNumber = Integer.parseInt( serialnumberField.getText() );
            String licenseCode = licensecodeField.getText();
            String contactName = contactNameField.getText();
            String companyName = companyField.getText();
            String location = locationField.getText();
            String expirationDate = (expirationDateField.getText().isEmpty()) ? null : expirationDateField.getText();
            String scannerModel = scannerModelField.getText();
            String version = versionField.getText();
            String purchaseDate = (purchaseDateField.getText().isEmpty()) ? null : purchaseDateField.getText();

            //get values from jspinners
            int numDesktop = ((SpinnerNumberModel) desktopsField.getModel()).getNumber().intValue();
            int numReaders = ((SpinnerNumberModel) readersField.getModel()).getNumber().intValue();
            int numVerifiers = ((SpinnerNumberModel) verifiersField.getModel()).getNumber().intValue();
            int numDesigners = ((SpinnerNumberModel) designersField.getModel()).getNumber().intValue();
            int numScanstation = ((SpinnerNumberModel) scanstationsField.getModel()).getNumber().intValue();
            int numCaptureStations = ((SpinnerNumberModel) remotestationsField.getModel()).getNumber().intValue();
            int numAmps = ((SpinnerNumberModel) ampsField.getModel()).getNumber().intValue();

            // Get radio button values
            boolean eform = eFormY.isSelected();
            boolean techsup = techSupY.isSelected();
            boolean firstline = firstLineY.isSelected();

            int entityId = -1;
            //Get Customer's entityId
            try {
                entityId = cOps.retrieveCustomer( contactName, companyName ).getEntityId();
            } catch( SQLException sqle ) {
                ExceptionUtils.handleException( this, sqle, "There was a problem updating the module information."
                                                            + "\nPlease check the log file for more information.",
                                                this.getClass() );
                return;
            }

            //Build the old module data
            Module oldModule = new Module( entityId,
                                        serialNumber,
                                        licenseCode,
                                        location,
                                        expirationDate,
                                        numDesktop,
                                        numReaders,
                                        numVerifiers,
                                        numDesigners,
                                        numScanstation,
                                        numCaptureStations,
                                        numAmps,
                                        eform,
                                        techsup,
                                        firstline,
                                        scannerModel,
                                        version,
                                        purchaseDate );

            //Build new module data
            Module newModule = new Module( entityId,
                                        newSerialNumber,
                                        licenseCode,
                                        location,
                                        expirationDate,
                                        numDesktop,
                                        numReaders,
                                        numVerifiers,
                                        numDesigners,
                                        numScanstation,
                                        numCaptureStations,
                                        numAmps,
                                        eform,
                                        techsup,
                                        firstline,
                                        scannerModel,
                                        version,
                                        purchaseDate );

            //passes in the 2 module objects to insertModule and catch errors
            try {
                if( mOps.updateModule( oldModule, newModule ) ) {
                    JOptionPane.showMessageDialog( rootPane, "Successfully added module." );
                    close( false );
                }
                else {
                    JOptionPane.showMessageDialog( rootPane, "Could not alter module. Please check data and try again." );
                }
            } catch( SQLException sqle ) {
                ExceptionUtils.handleException( this, sqle, "There was a problem adding module information."
                                                            + "\nPlease check the log file for more details.",
                                                this.getClass() );
                return;
            }
        }

    }//GEN-LAST:event_applyChangesButtonActionPerformed

    private void backButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backButtonActionPerformed
        close( false );
    }//GEN-LAST:event_backButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JSpinner ampsField;
    private javax.swing.JButton applyChangesButton;
    private javax.swing.JButton backButton;
    private javax.swing.JTextField companyField;
    private javax.swing.JLabel companyLabel;
    private javax.swing.JTextField contactNameField;
    private javax.swing.JSpinner designersField;
    private javax.swing.JSpinner desktopsField;
    private javax.swing.ButtonGroup eFormBtnGrp;
    private javax.swing.JRadioButton eFormN;
    private javax.swing.JRadioButton eFormY;
    private javax.swing.JTextField expirationDateField;
    private javax.swing.ButtonGroup firstLineBtnGrp;
    private javax.swing.JRadioButton firstLineN;
    private javax.swing.JRadioButton firstLineY;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField licensecodeField;
    private javax.swing.JTextField locationField;
    private javax.swing.JTextField purchaseDateField;
    private javax.swing.JSpinner readersField;
    private javax.swing.JSpinner remotestationsField;
    private javax.swing.JTextField scannerModelField;
    private javax.swing.JSpinner scanstationsField;
    private javax.swing.JTextField serialnumberField;
    private javax.swing.JRadioButton techSupN;
    private javax.swing.JRadioButton techSupY;
    private javax.swing.ButtonGroup techSupportBtnGrp;
    private javax.swing.JLabel usernameLabel;
    private javax.swing.JLabel usernameLabel1;
    private javax.swing.JLabel usernameLabel10;
    private javax.swing.JLabel usernameLabel11;
    private javax.swing.JLabel usernameLabel2;
    private javax.swing.JLabel usernameLabel3;
    private javax.swing.JLabel usernameLabel4;
    private javax.swing.JLabel usernameLabel5;
    private javax.swing.JLabel usernameLabel6;
    private javax.swing.JLabel usernameLabel7;
    private javax.swing.JLabel usernameLabel8;
    private javax.swing.JLabel usernameLabel9;
    private javax.swing.JSpinner verifiersField;
    private javax.swing.JTextField versionField;
    // End of variables declaration//GEN-END:variables
}
